// A script to handle uploads via Ajax


    // global object that contains Ajax.PeriodicalUpdater 
    var updater;
	this.formFieldId = null;
  
    // main function for upload monitoring
    function submitPostUsingAjax(trgID, progressBar, formFieldId) {
		//console.log("submit!");                
		
		this.formFieldId = formFieldId;
		this.trgID = trgID;
		this.progressBar = progressBar;
		//console.log("trg id: " + trgID + " progress bar: " + progressBar + " form field id: " + formFieldId);

		try {
            // get upload status
		updater = new PeriodicalExecuter(function(pe){
					new Ajax.Request ("/uploader/", {
					method:'get',
                onSuccess:function(transport) {
				        if (transport.responseText != "") {         
                        						
						$(progressBar).style.visibility = 'visible';
                        $(progressBar).style.width = transport.responseText + '%';
						//console.log("response: " + transport.responseText);
																		
						}
					//console.log("trgID: " + trgID);					
					//console.log("iframe contents: "+ $(trgID).contentWindow.document.body.innerHTML);
					
					
					if ($(trgID).contentWindow.document.body.innerHTML != "") {
						//console.log("iFrame not empty");
						$(progressBar).style.visibility = 'visible';
						$(progressBar).style.width = 100 + '%';
						//console.log("finished 1!");
						handleUploadFinished();
					}
                }})                                                                  
            }.bind(this),0.2);
        } catch(e) {
            alert('submitPostUsingAjax() failed, reason: ' + e);
        } finally {
        }                                       
        return false;
    }                                                                       
        
    // executes function after page loaded
    function addLoadEvent(func) {
	//console.log("add load event");
        var oldonload = window.onload;       
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                oldonload();
                func();
            }
        }
    }                                       
        
    // this function will be executed after "target" IFRAME content changed
    function handleUploadFinished() {
        // stop updater manually
	//console.log("finished 2!");
			

        if ((typeof updater != 'undefined')&&(updater != null)) {
	    	updater.stop();
            	updater = null;
		$(this.formFieldId).clear();
        	$(this.formFieldId).value = location.protocol + "//" + location.host + "/upload/" + $(this.trgID).contentWindow.document.body.innerHTML;
		//console.log("form field id: " + this.formFieldId);
		var bodyElement = findParentNode("body",$(this.formFieldId));
		bodyElement.getElementsByClassName("hideLink")[0].onclick();
        }                                                                   
    } 
